﻿using BackToCOS.Jobs;
using Quartz;
using Quartz.Impl;
using Quartz.Impl.Triggers;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using Topshelf;

namespace BackToCOS
{
   public  class BackupServiceRunner : ServiceControl, ServiceSuspend
    {
        private  IScheduler _scheduler;

        public BackupServiceRunner()
        {
           
        }

        public bool Start(HostControl hostControl)
        {
            //自定义配置
            NameValueCollection properties = new NameValueCollection();
       
     
            //可以默认配置
            ISchedulerFactory factory = new StdSchedulerFactory();


            //1、通过调度工厂获得调度器
            _scheduler =  factory.GetScheduler().GetAwaiter().GetResult();
            //2、开启调度器
            _scheduler.Start();
            //3、创建一个Corn表达式触发器
            CronTriggerImpl trigger = new CronTriggerImpl();
            // corn * * * * * ? 每秒执行一次(测试)
            //corn 0 0 3 0 0 1,3,5  星期一、三、五的3点执行
            //每天3点备份
            trigger.CronExpressionString = "0 0 3 1/1 * ?";
            trigger.Name = "备份时间触发器";
            //4、创建任务
            var jobDetail = JobBuilder.Create<BackupJob>()
                            .WithIdentity("filejob", "backup")
                            .Build();
            //5、将触发器和任务器绑定到调度器中
            _scheduler.ScheduleJob(jobDetail, trigger).GetAwaiter().GetResult(); 
            return true;
        }

        public bool Stop(HostControl hostControl)
        {
            _scheduler.Shutdown(false);
            return true;
        }

        public bool Continue(HostControl hostControl)
        {
            _scheduler.ResumeAll();
            return true;
        }

        public bool Pause(HostControl hostControl)
        {
            _scheduler.PauseAll();
            return true;
        }
    }
}
